<template>
    <!-- 需求表单开始 -->
    <div v-for="(requirement, reqIndex) in requirements" :key="reqIndex" class="sjplatform-form-edit-item">
        <el-form-item :key="requirement.id" :label="'需求' + (reqIndex + 1) + '：'">
            <el-input class="item-input" v-model="requirement.title" placeholder="请输入需求标题" />
            <el-tooltip :content="'删除需求' + (reqIndex + 1)" placement="bottom" effect="light">
                <i class="del-icon" @click="delRequirement(reqIndex)"></i>
            </el-tooltip>
        </el-form-item>
        <el-form-item label="描述：">
            <el-input v-model="requirement.mark" type="textarea" placeholder="请输入需求描述" />
        </el-form-item>
        <!-- <el-form-item label="父级：" v-if="requirement.sort > 1"> -->
        <el-form-item label="父级：">
            <el-select v-model="requirement.pId" clearable placeholder="请选择父级功能"
                @update:modelValue="setRequirementPName(requirement, requirement.pId)">
                <el-option
                    v-for="r in parentRequirements.filter(r => r.id !== requirement.id && r.sort < requirement.sort && r.title != '')"
                    :key="r.id" :label="r.title" :value="r.id" />
            </el-select>
        </el-form-item>

        <!-- 功能 -->
        <div v-for="(item, itemIndex) in requirement.childFeatures" :key="itemIndex" class="form-child">
            <el-form-item :key="item.id" :label="'功能' + (itemIndex + 1) + '：'">
                <el-input class="item-input" v-model="item.title" placeholder="请输入功能标题" />
                <el-tooltip :content="'删除功能' + (reqIndex + 1)" placement="bottom" effect="light">
                    <i class="del1-icon" @click="removeItem(reqIndex, itemIndex)"></i>
                </el-tooltip>
            </el-form-item>
            <el-form-item label="描述：">
                <el-input v-model="item.mark" type="textarea" placeholder="请输入功能描述" />
            </el-form-item>
            <el-form-item label="父级：" v-if="item.sort > 1">
                <el-select v-model="item.pId" clearable placeholder="请选择父级功能"
                    @update:modelValue="setFeaturePName(reqIndex, item, item.pId)">
                    <el-option
                        v-for="f in requirement.childFeatures.filter(f => f.id !== item.id && f.sort < item.sort && f.title != '')"
                        :key="f.id" :label="f.title" :value="f.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="类型：">
                <el-select v-model="item.type" clearable placeholder="请选择功能类型">
                    <el-option v-for="r in projectStore.requirementType" :key="r.value" :label="r.label"
                        :value="r.value" />
                </el-select>
            </el-form-item>
            <!--接口-->
            <template v-if="item.type == 2">
                <el-form-item label="参数：">
                    <el-input v-model="item.parameters" placeholder="请输入参数" />
                </el-form-item>
                <el-form-item label="返回值：">
                    <el-input v-model="item.rValue" placeholder="请输入返回值" />
                </el-form-item>
            </template>
            <!--列表-->
            <template v-if="item.type == 3">
                <el-form-item label="列名：">
                    <el-input v-model="item.columns" placeholder="请输入列表，多个列名之间用半角逗号隔开" />
                </el-form-item>
            </template>
        </div>
        <div class="operation-button">
            <el-tooltip :content="'添加需求' + (reqIndex + 1) + '的子项'" placement="bottom" effect="light">
                <i class="addchild-icon" @click="addItem(reqIndex, requirement.id, requirement.title)"></i>
            </el-tooltip>
        </div>
    </div>
    <!-- 需求表单结束 -->

    <el-form label-width="100px">
        <el-form-item label="需求操作：">
            <el-tooltip content="添加需求" placement="bottom" effect="light">
                <i class="add-icon" @click="addRequirementItem"></i>
            </el-tooltip>
            <el-tooltip content="导入需求" placement="bottom" effect="light">
                <i class="import-icon"></i>
            </el-tooltip>
            <el-tooltip content="生成需求文档" placement="bottom" effect="light">
                <i class="build-icon"></i>
            </el-tooltip>
        </el-form-item>
        <el-form-item label="附件：">
            <FileUpload ref="fileUpload" :historyFileList="historyFileList" @file-delete="handleFileDeleted" />
        </el-form-item>
    </el-form>

</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits } from 'vue';
import FileUpload from "../../Common/FileUpload.vue";
import { useProjectTable } from "../../../hooks/ProjectManager/Start/useProjectTable";
import { useProjectRequirement } from "../../../hooks/ProjectManager/Plan/useProjectRequirement";
import commonUtil from '../../../utils/common';

let historyFileList = ref();
let { projectTable, projectStore, getProjectDoc, deleteProjectDoc } = useProjectTable(1, 10);
let { getRequirementDetailByProjectId, getRequirementDetailByRequirementId } = useProjectRequirement(1, 10);

//父级需求
let parentRequirements = ref([]);

//接收参数
let receivedProps = defineProps({
    modelValue: Array,
    rId: String,
    rName: String,
    changeType: Number,
    info: {
        type: Object,
        required: true
    }
});
if (receivedProps.rId) {
    // console.log("receivedProps.info", receivedProps.info)
    // console.log("receivedProps.rId", receivedProps.rId)
    // console.log("receivedProps.rName", receivedProps.rName)
    // parentRequirements.value.push({ id: receivedProps.rId, title: receivedProps.rName, sort: 0 });
    // if (receivedProps.changeType == 2) {
    //     getRequirementDetailByRequirementId(receivedProps.rId);
    // }
}
let emit = defineEmits(['update:modelValue']);
//父组件传递的有值则用父组件的，没有则为空数组
let requirements = ref([]);// ref(receivedProps.modelValue ? [...receivedProps.modelValue] : []);

// 监听局部数据的变化并发出更新事件，确保双向绑定
watch(requirements, (newValue) => {
    emit('update:modelValue', newValue);
}, { deep: true });

// 监听 receivedProps 变化
watch(() => receivedProps.rId, (newValue, oldValue) => {
    let prIndex = parentRequirements.value.findIndex(r => r.sort === 0 && r.id === oldValue);
    if (prIndex !== -1) {
        // 如果找到了，则更新该对象
        parentRequirements.value[prIndex] = {
            id: newValue,
            title: receivedProps.rName,
            sort: 0
        };
    } else {
        // 如果没找到且 newValue 和 receivedProps.rName 存在，插入新的对象
        if (newValue && receivedProps.rName) {
            parentRequirements.value.push({
                id: newValue,
                title: receivedProps.rName,
                sort: 0
            });
        }
    }

    //需求变更
    if (receivedProps.changeType == 2) {
        getRequirementDetailByRequirementId(newValue).then(res => {
            requirements.value = projectStore.requirementModel.requirements;
        });
    }
}, { deep: true });


/* if (projectStore.requirementModel.projectId) {
    getRequirementDetailByProjectId(projectStore.requirementModel.projectId).then(() => {
        //如果需求主表ID为空则表示还没有配置，生成一个主ID并给projectId赋值
        if (!projectStore.requirementModel.id) {
            projectStore.requirementModel.id = commonUtil.Methods.generateGUID();
            projectStore.requirementModel.projectId = projectStore.projectModel.id;
        }
    })
} */


//附件
if (projectStore.projectModel.id) {
    getProjectDoc(projectStore.projectModel.id, 2).then(() => {
        historyFileList.value = projectTable.documentList;
    });
}


//添加需求
function addRequirementItem() {
    // 添加新的需求对象
    requirements.value.push({
        id: commonUtil.Methods.generateGUID(),
        projectId: projectStore.projectModel.id,
        mId: projectStore.requirementModel.id,
        title: '',
        mark: '',
        pId: '',
        pName: '',//父级需求
        sort: requirements.value.length + 1,//排序
        childFeatures: [] // 初始化子项列表
    });
    parentRequirements.value.push(
        {
            id: commonUtil.Methods.generateGUID(),
            title: '',
            sort: requirements.value.length + 1,//排序
        }
    )
}
//删除需求
function delRequirement(reqIndex) {
    // 向指定需求的子项列表中添加新子项
    requirements.value.splice(reqIndex, 1);
}
//添加功能 
function addItem(reqIndex, rId, rName) {
    // 向指定需求的子项列表中添加新子项
    if (!requirements.value[reqIndex].childFeatures) {
        requirements.value[reqIndex].childFeatures = [];
    }
    requirements.value[reqIndex].childFeatures.push({
        id: commonUtil.Methods.generateGUID(),
        projectId: projectStore.projectModel.id,
        rId: rId,
        rName: rName,
        title: '',
        mark: '',
        type: null,//功能类型
        pId: '',
        pName: '',//父级功能
        parameters: '',//参数
        rValue: '',//返回值
        columns: '',//列名
        sort: requirements.value[reqIndex].childFeatures.length + 1,//排序
    });
}
//删除功能
function removeItem(reqIndex, itemIndex) {
    // 从指定需求的子项列表中删除指定子项
    requirements.value[reqIndex].childFeatures.splice(itemIndex, 1);
}

//设置需求父级名称
function setRequirementPName(item, value) {
    // 找到对应的父级需求
    const parent = requirements.value.find(r => r.id === value);
    // 如果找到了父级需求，设置 pId 和 pName
    if (parent) {
        item.pId = parent.id;
        item.pName = parent.title;
    }
}

//设置功能父级名称
function setFeaturePName(reqIndex, item, value) {
    // 找到对应的父级需求
    const parent = requirements.value[reqIndex].childFeatures.find(r => r.id === value);

    // 如果找到了父级需求，设置 pId 和 pName
    if (parent) {
        item.pId = parent.id;
        item.pName = parent.title;
    }
}

// 处理文件删除事件
async function handleFileDeleted(objectId) {
    if (await deleteProjectDoc(objectId)) {
        historyFileList.value = historyFileList.value.filter(file => file.objectId !== objectId);
    }
}
</script>